package com.nd.android.u.ui.chatUiUtils;

import java.io.File;
import java.io.IOException;
import java.lang.Thread.State;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.common.android.utils.audio.AudioPlayer;
import com.common.android.utils.audio.AudioPlayer.onPlayFinishListener;
import com.common.android.utils.audio.AudioPlayer.onPlayStopListener;
import com.nd.android.u.allCommonUtils.LogUtils;
import com.nd.android.u.controller.ChatConst.MessageContentType;
import com.nd.android.u.controller.MessageConst.MessageCommonState;
import com.nd.android.u.controller.MessageConst.MessageState;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.controller.observer.MessageDispatcher;
import com.product.android.ui.widget.AnimImageView;

/**
 * ClassName:AudioQuenePlayManager Function: 连续播放音频管理类 Reason:
 * 用户在聊天界面点击音频对话的时候，如果接下来的还是音频记录并且是同侧的，则要自动播放下一条
 * 
 * @author cb
 * @version
 * @since Ver 1.2
 * @Date 2013 2013-5-31 上午11:08:35
 * 
 * @see
 */
public class AudioQuenePlayManager {
	private static AudioQuenePlayManager mInstance;
	private Context mContext;
	private List<IMessageDisplay> mMessageList;
	private IMessageDisplay mPlayingMessage;
	private playTask mTask = new playTask();
	private boolean mIsPlaying=false;

	// 保存当前播放的语音是否未读（因为在播放完成之前就要把它置为已读，但是在播放完成之后又要用到这个值）
	private boolean mPlayingMessageRead = false;

	public static AudioQuenePlayManager getInstance() {
		if (mInstance == null) {
			mInstance = new AudioQuenePlayManager();
		}
		return mInstance;
	}

	public AudioQuenePlayManager() {
		AudioPlayer.getInstance().setOnPlayFinishListener(playFinishListener);
		AudioPlayer.getInstance().setOnPlayStopListener(stopListener);
	}

	/**
	 * @n<b>函数名称</b> :setDetailList
	 * @brief 设置数据源
	 * @see
	 * @since Ver 1.2
	 * @param @param detailList
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-8-8上午10:01:33
	 */
	public void setDetailList(List<IMessageDisplay> detailList) {
		mMessageList = detailList;
	}

	/**
	 * @n<b>函数名称</b> :startQuenePlay
	 * @brief 播放音频
	 * @see
	 * @since Ver 1.2
	 * @param @param message
	 * @param @param context
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-8-8上午10:01:53
	 */
	public void startQuenePlay(IMessageDisplay message, Context context) {
		mContext = context;
		if (message == null || context == null) {
			LogUtils.d("debug", "message==null");
			return;
		}
		if (mMessageList == null || mMessageList.size() == 0) {
			LogUtils.d("debug", "mDetailList==null && mDetailList.size()==0");
			return;
		}
		if (mPlayingMessage != null) {
			// 当前有正在播放的语音
			stopPlay();
			if (mPlayingMessage == message) {
				// 正在播放的就是现在要播的，相当于停止
				mPlayingMessage = null;
				return;
			}
		}
		// 设置当前播放的语音，并开启线程循环改变entity里的current值，用来控制listview的刷新显示播放语音的动画
		mPlayingMessage = message;
		mPlayingMessageRead = mPlayingMessage.isRead();
		mIsPlaying=true;
		mPlayingMessage.setCurrent(AnimImageView.CURRENT_STOP);
		try {
			File file = new File(mPlayingMessage.getPath());
			AudioPlayer.getInstance().play(file, context);
			startTask();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @n<b>函数名称</b> :startTask
	 * @brief 开始播放
	 * @see
	 * @since Ver 1.2
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-8-8上午10:05:23
	 */
	private void startTask() {
		State state = mTask.getState();
		if (Thread.State.NEW == state) {
			mTask.start();
		} else if (Thread.State.TERMINATED == state) {
			mTask = new playTask();
			mTask.start();
		}
	}

	/**
	 * @n<b>函数名称</b> :stopPlay
	 * @brief 停止播放
	 * @see
	 * @since Ver 1.2
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-8-8上午10:05:30
	 */
	public void stopPlay() {
		stopPlay(true);
	}

	/**
	 * @n<b>函数名称</b> :stopPlayAndSetCureentNull
	 * @brief 停止播放并把当前播放的消息置空
	 * @reason 修复BUG #33326:【聊天】在播放录音过程中，锁屏，再解锁屏幕后，要按两次录音才会播放。
	 * @see
	 * @version Ver 1.3.x
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2014-1-22上午11:39:16
	 */
	public void stopPlayAndSetCureentNull() {
		stopPlay(true);
		mPlayingMessage = null;
	}

	/**
	 * @n<b>函数名称</b> :stopPlay
	 * @brief 停止播放
	 * @see
	 * @since Ver 1.2
	 * @param @param notifyAudioPlayToStop 用于判断是否通知audioplayer停止
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-8-8上午10:05:36
	 */
	public void stopPlay(boolean notifyAudioPlayToStop) {
		if (notifyAudioPlayToStop) {
			// 通知AudioPlayer停止
			AudioPlayer.getInstance().stopPlay();
		}
			// 通知界面刷新
		if (mPlayingMessage==null){
			return;
		}
		mPlayingMessage.setCurrent(AnimImageView.CURRENT_STOP);
		mIsPlaying=false;
		MessageDispatcher.getInstance().notifyMessageStateChanged(mPlayingMessage, MessageState.PLAYING);
	}

	/**
	 * ClassName:playTask Function: 动画线程 Reason: TODO ADD REASON
	 * 
	 * @author cb
	 * @version AudioQuenePlayManager
	 * @since Ver 1.2
	 * @Date 2013 2013-8-8 上午10:07:03
	 * 
	 * @see
	 */
	private class playTask extends Thread {
		@Override
		public void run() {
		    int current=0;
		    if(mPlayingMessage!=null){
		        current = mPlayingMessage.getCurrent();
		    }
//			int current = mPlayingMessage.getCurrent();
			while (mPlayingMessage != null && mIsPlaying) {
				current = mPlayingMessage.getCurrent();
				current++;
				if (current > 2) {
					current=0;
				}
				mPlayingMessage.setCurrent(current);
				Message message=refreshHandler.obtainMessage();
				message.obj=mPlayingMessage;
				refreshHandler.sendMessage(message);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private Handler refreshHandler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			IMessageDisplay message=(IMessageDisplay) msg.obj;
			MessageDispatcher.getInstance().notifyMessageStateChanged(message, MessageState.PLAYING);
		};
	};

	/**
	 * field:playFinishListener Function: 播放完成监听
	 * 
	 * @author cb
	 * @since Ver 1.2
	 * @Date 2013 2013-8-8 上午10:07:29
	 */
	private onPlayFinishListener playFinishListener = new onPlayFinishListener() {
		@Override
		public void onFinish() {
			if (mPlayingMessage == null) {
				return;
			}
			// 先停止播放
			AudioPlayer.getInstance().stopPlay();
			mIsPlaying=false;
			mPlayingMessage.setCurrent(AnimImageView.CURRENT_STOP);
			if (!mPlayingMessageRead) {
				MessageDispatcher.getInstance().notifyMessageStateChanged(mPlayingMessage, MessageState.PLAYING);
			} else {
				// 该消息已读，通知界面刷新且不继续往下播
				MessageDispatcher.getInstance().notifyMessageStateChanged(mPlayingMessage, MessageState.PLAYING);
				mPlayingMessage = null;
				return;
			}
			if (mPlayingMessage.isFromSelf()) {
				// 如果是自己的语音消息，不连播
				mPlayingMessage = null;
				return;
			}
			int index = mMessageList.indexOf(mPlayingMessage);
			if (index == mMessageList.size() - 1) {
				// 已经是最后一个
				mPlayingMessage = null;
				return;
			}
			for (int i = index + 1, count = mMessageList.size(); i < count; i++) {
				IMessageDisplay next = mMessageList.get(i);
				if (next != null && !next.isRead() && !next.isFromSelf()
						&& isAudioMessage(next)) {
					// 未读的且是收到的语音消息，继续播
					startQuenePlay(next, mContext);
					next.setIsRead(MessageCommonState.DONE,true);
					return;
				}
			}
			mPlayingMessage = null;
			return;
		}
	};

	private onPlayStopListener stopListener = new onPlayStopListener() {
		@Override
		public void onStop() {
			stopPlay(false);
		}
	};

	/**
	 * 是否语音消息
	 * <br>Created 2014-5-6 下午7:46:25
	 * @param msg
	 * @return
	 * @author       cb
	*/
	private boolean isAudioMessage(IMessageDisplay msg) {
		int type = msg.getMessageContentType();
		if (type==MessageContentType.AUDIO || type==MessageContentType.OLD_AUDIO) {
			return true;
		}
		String filename = msg.getPath();
		if (TextUtils.isEmpty(filename) || !filename.endsWith(".amr")) {
			return false;
		}
		File file = new File(filename);
		if (file == null || !file.exists()) {
			return false;
		}
		return true;
	}
}
